import { CancelExecutor, Cancelr, CancelTokenSource} from "../types/index";

import Cancel from './Cancel'
interface ResolvePromise{
    (reason?: Cancel ): void
}

export default class CancelToken{
    promise: Promise<Cancel>
    reason?: Cancel

    constructor(executer: CancelExecutor) {
        // TODO
        let resolvePromise: any
        this.promise = new Promise<Cancel>(resolve=>{
            resolvePromise = resolve
        })

        executer(message =>{
            if(!this.reason){
                return
            }
            this.reason = new Cancel(message)
            resolvePromise((this.reason))
        })

    }

    throwIfRequest(){
        if(this.reason){
            throw this.reason
        }
    }

    static source(): CancelTokenSource{
        let cancel!: Cancelr
        const token =  new CancelToken(c=>{
            cancel = c
        })

        return {
            cancel,
            token
        }
    }
}